package com.cqhz.quwan.ui.base

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import com.blankj.utilcode.util.LogUtils
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.cqhz.quwan.APP
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.ui.buy.BettingMachineActivity
import com.cqhz.quwan.ui.main.MainActivity
import com.cqhz.quwan.ui.main.match.MatchAnalysisActivity
import com.cqhz.quwan.util.JSBridgeInterface
import quickcore.webview.WebViewListener
import quickcore.webview.WebViewSetup
import java.util.*


abstract class AbsWebFragment : AbsFragment(), WebViewListener {
    private var isOther: Boolean = false
    private var isOpen: Boolean = false
    private var startUrl: String? = null
    private val mHandler = Handler(Looper.getMainLooper())
    private var valueCallbacks: ValueCallback<Array<Uri>>? = null
    private var valueCallback: ValueCallback<Uri>? = null
    override fun setTitleView(title: String?) {

    }

    open fun loadUrlCallback(): ((String) -> Unit)? {
        return null
    }

    open fun goBackCallback(): ((WebView) -> Unit)? {
        return null
    }

    override fun pageStart(view: WebView?, url: String?, favicon: Bitmap?) {
        startUrl = url
    }

    override fun loadUrl(webView: WebView?, isWebScheme: Boolean, scheme: String?, url: String?): Boolean {
        if (!isWebScheme) {
            isOther = true
            val uri = Uri.parse(url)
            isOpen = try {
                val intent = Intent(Intent.ACTION_VIEW, uri)
                // 跳转指定协议打开外部应用
                startActivity(intent)
                true
            } catch (exception: ActivityNotFoundException) {
                // 这个时候可以理解为用户没有安装指定的应用
                false
            }

        } else {
            isOther = false
            loadUrlCallback()?.invoke(url ?: "")
            if (startUrl != null && startUrl.equals(url)) {
                this.webView.loadUrl(url)
            } else {
                return false
            }
        }
        return true
    }

    override fun onDownload(url: String?) {
        if (isOther && !isOpen) {
            val uri = Uri.parse(url)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        } else if (!isOther && !isOpen) {
            //普通协议，调用系统浏览器下载
            val uri = Uri.parse(url)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
    }

    override fun onOpenFile(has: Boolean, callback: ValueCallback<Array<Uri>>?, callback2: ValueCallback<Uri>?) {
        valueCallbacks = callback
        valueCallback = callback2
        checkPermissions()
    }

    private fun createUploadDialog(): AlertDialog {
        return AlertDialog.Builder(context).setTitle("请选择操作").setItems(arrayOf("打开相册", "取消"), { _, which ->
            when (which) {
                0 -> {
                    val intent = Intent(Intent.ACTION_GET_CONTENT)
                    intent.addCategory(Intent.CATEGORY_OPENABLE)
                    intent.type = "image/*"
                    startActivityForResult(Intent.createChooser(intent, "请选择"), 0x99)
                }
                1 -> {
                    if (null != valueCallback) {
                        valueCallback!!.onReceiveValue(null)
                        valueCallback = null
                    } else if (null != valueCallbacks) {
                        valueCallbacks!!.onReceiveValue(null)
                        valueCallbacks = null
                    }
                }
            }
        }).setOnCancelListener {
            if (null != valueCallback) {
                valueCallback!!.onReceiveValue(null)
                valueCallback = null
            } else if (null != valueCallbacks) {
                valueCallbacks!!.onReceiveValue(null)
                valueCallbacks = null
            }
        }.create()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                0x99 -> {
                    if (null != valueCallback) {
                        val result = if (data == null || resultCode != Activity.RESULT_OK) {
                            null
                        } else {
                            data.data
                        }
                        valueCallback!!.onReceiveValue(result)
                        valueCallback = null
                    } else if (null != valueCallbacks) {
                        val result = (if (data == null || resultCode != Activity.RESULT_OK) {
                            null
                        } else {
                            data.data
                        }) ?: return
                        valueCallbacks!!.onReceiveValue(arrayOf(result))
                        valueCallbacks = null
                    }
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            if (null != valueCallback) {
                valueCallback!!.onReceiveValue(null)
                valueCallback = null
            } else if (null != valueCallbacks) {
                valueCallbacks!!.onReceiveValue(null)
                valueCallbacks = null
            }
        }
    }

    private fun createPermissionTipDialog(): Dialog {
        return AlertDialog.Builder(context)
                .setTitle("警告").setMessage("请求权限申请异常。请前往应用设置页面允许必要的权限，否则将无法正常运行应用")
                .setNegativeButton("取消") { dialog, _ ->
                    dialog.dismiss()
                }.setPositiveButton("确认") { dialog, _ -> dialog.dismiss() }
                .setCancelable(false)
                .create()
    }

    private fun checkPermissions() {
        if (ContextCompat.checkSelfPermission(context(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_DENIED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity!!,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                if (null != valueCallback) {
                    valueCallback!!.onReceiveValue(null)
                    valueCallback = null
                } else if (null != valueCallbacks) {
                    valueCallbacks!!.onReceiveValue(null)
                    valueCallbacks = null
                }
                createPermissionTipDialog().show()

            } else {
                ActivityCompat.requestPermissions(activity!!, arrayOf(""), 0x01)
            }
        } else {
            createUploadDialog().show()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0x01) {
            val temp = ArrayList<String>()

            for (i in grantResults.indices) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(activity!!, permissions[i])) {
                        createPermissionTipDialog().show()
                        if (null != valueCallback) {
                            valueCallback!!.onReceiveValue(null)
                            valueCallback = null
                        } else if (null != valueCallbacks) {
                            valueCallbacks!!.onReceiveValue(null)
                            valueCallbacks = null
                        }
                        return
                    } else {
                        temp.add(permissions[i])
                    }
                }
            }
            val tempArray = arrayOfNulls<String>(temp.size)
            if (tempArray.isNotEmpty()) {
                ActivityCompat.requestPermissions(activity!!, temp.toArray(tempArray), 0x01)
                return
            }
            createUploadDialog().show()
        }
    }

    lateinit var webView: WebView

    override fun initView() {
        with(view) {
            webView = view!!.findViewById(webViewIdRes())
        }
        val dir = context!!.getDir("database", Context.MODE_PRIVATE).path
        WebViewSetup.builder()
                .setWebViewClient(this)
                .setLocationDbPath(dir)
                .setCacheMode(WebSettings.LOAD_NO_CACHE)
                .build().setupWebView(webView)
        val jsBridge = JSBridgeInterface()
        jsBridge.toBettingCallBack = { periodId, typeId ->
            val cl = APP.get()!!.currentLottery.find {
                it.id == typeId
            }
            if (cl != null) {
                val intent = Intent(context, BettingMachineActivity::class.java)
                intent.putExtra(KeyContract.PeriodNum, cl.period)
                intent.putExtra(KeyContract.LotteryId, cl.id)
                startActivity(intent)
            } else {
                showToast("网络加载失败，请重试")
            }
        }
        jsBridge.goHomeCallBack = {
            val intent = Intent(context, MainActivity::class.java)
            startActivity(intent)
        }
        jsBridge.finishCallBack = {
            //            if (webView.canGoBack()&&!isHidden){
//                webView.goBack()
//            }
            goBackCallback()?.invoke(webView)
        }

        /**
         * 赛事分析
         */
        jsBridge.callMtchAnalysis = { matchId, leagueId ->
            LogUtils.e("callMtchAnalysis", "matchId = $matchId; leagueId = $leagueId")
            MatchAnalysisActivity.start(context, matchId, leagueId)
        }

        webView.addJavascriptInterface(jsBridge, "Android")
        (activity as MainActivity).onBackListener = {
            if (webView.canGoBack() && !isHidden) {
                webView.goBack()
                true
            } else {
                false
            }
        }
    }


    override fun onResume() {
        webView.onResume()
        super.onResume()
    }


    override fun onDestroy() {
        super.onDestroy()
        webView.destroy()
    }

    override fun onPause() {
        super.onPause()
        webView.onPause()
    }

    fun canGoBack(): Boolean {
        return webView.canGoBack()
    }

    fun goBack() {
        webView.goBack()
    }

    abstract fun webViewIdRes(): Int
}